import 'package:flutter/material.dart';
import 'package:x3_form_core/x3_form_core.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/x3_component_core.dart';
import '../widget/advanced_filter_item_container.dart';
import '../widget/advanced_filter_fuzzy_search_screen.dart';

mixin AdvancedFilterInputSearchMixin<T extends StatefulWidget> on State<T> {
  /// 高度
  final double rowHeight = 32;

  /// 模型
  BaseAdvancedFilterModel get model;

  ///子页面弹窗高度
  double get fuzzySearchScreenHeight;

  ///子页(模糊搜索弹窗页面)请求链接
  String get inputApi => getInputSearchModel().inputApi;

  ///子页面(模糊搜索弹窗页面)请求类型
  BaseHttpMethodEnum get method => getInputSearchModel().method;

  /// 子页面是否分页
  bool get isPaging => getInputSearchModel().isPaging;

  /// 子页面是否不需要搜索框
  bool get notNeedSearch => getInputSearchModel().notNeedSearch;

  /// 子页面请求参数
  Map<String, dynamic> get params => getInputSearchModel().params;

  ///子页面(模糊搜索弹窗页面)item
  Widget Function(Map<String, dynamic> item, bool isSelect) get childSearchItem => getChildSearchItem;

  ///子页面item唯一key
  String get childOnlyKey => getInputSearchModel().childOnlyKey;

  ///子页面item唯一value
  String get childOnlyValue => getInputSearchModel().childOnlyValue;

  String get childSearchKey => getInputSearchModel().childSearchKey;

  /// 共享类
  BaseAdvancedFilterProvider get baseRequestFormProvider => BaseAdvancedFilterProvider.of(context, listen: false);

  /// 选中列表
  List<BaseKeyValueModel> selectedList = [];

  /// 选中的id - 唯一标识
  List<String> get selectedListKey => selectedList.map((e) => e.key.toString()).toList();

  TextStyle get hintStyle => Theme.of(context).inputDecorationTheme.hintStyle;

  @override
  void initState() {
    var data = baseRequestFormProvider.getDataSource(model);
    if (data != null) {
      if (data is List) selectedList.addAll(data.map((e) => BaseKeyValueModel.fromJson(e)).toList());
      if (data is Map) selectedList.add(BaseKeyValueModel.fromJson(data));
    }

    /// 重置监听
    baseRequestFormProvider.resetStream.listen((e) {
      this.selectedList.clear();
      var data = baseRequestFormProvider.getDataSource(model);
      if (data != null) {
        if (data is List) selectedList.addAll(data.map((e) => BaseKeyValueModel.fromJson(e)).toList());
        if (data is Map) selectedList.add(BaseKeyValueModel.fromJson(data));
      }
      if (mounted) setState(() {});
    });
    initStateEvent();
    super.initState();
  }

  /// 添加初始化事件
  void initStateEvent() {}

  /// 创建 item
  Widget buildItemContainer() {
    return AdvancedFilterItemContainer(
      isRequired: model.required,
      title: model.name,
      child: _buildInputContent(),
    );
  }

  Widget _buildInputContent() {
    return InkWell(
      onTap: _openFuzzySearchScreen,
      child: Container(
        height: rowHeight,
        decoration: BoxDecoration(color: Colors.white, border: Border.all(color: Color(0xFFDFDFDF)), borderRadius: BorderRadius.circular(2)),
        child: Row(children: [
          _buildPrefixIcon(),
          model.inputType == BaseAdvancedFilterType.InputSearchSingleChoice ? _buildSingleChoice() : _buildMultipleChoiceInput(),
          if (selectedList.isNotEmpty) _buildClean(),
        ]),
      ),
    );
  }

  Widget _buildMultipleChoiceInput() {
    return Expanded(
      child: selectedList.isEmpty
          ? Text(model.note, maxLines: 1, overflow: TextOverflow.ellipsis, style: hintStyle)
          : ListView.separated(
              shrinkWrap: true,
              itemCount: selectedList.length,
              scrollDirection: Axis.horizontal,
              itemBuilder: (BuildContext context, int index) {
                return Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text('[', style: BaseStyles.bodyMedium(context)),
                    Text("${selectedList[index].key}", style: TextStyle(fontSize: 13, color: Color(0xFF868686))),
                    Text(']', style: BaseStyles.bodyMedium(context)),
                    Text("${selectedList[index].value}", style: BaseStyles.bodyMedium(context)),
                  ],
                );
              },
              separatorBuilder: (BuildContext context, int index) {
                return Container(width: 16, alignment: Alignment.center, child: Text("/"));
              },
            ),
    );
  }

  Widget _buildSingleChoice() {
    String _text = selectedList.isNotEmpty ? _showText(selectedList) : model.note;
    return Expanded(child: Text(_text, maxLines: 1, overflow: TextOverflow.ellipsis, style: selectedList.isNotEmpty ? BaseStyles.bodyMedium(context) : hintStyle));
  }

  /// 搜索小图标
  Widget _buildPrefixIcon() {
    return Padding(
      padding: const EdgeInsets.only(left: 8.0, right: 2.0),
      child: Icon(BaseIconData.x3Search, size: 18, color: BaseFormTheme.hintColor),
    );
  }

  /// 清空文本信息
  Widget _buildClean() {
    return Container(
      margin: EdgeInsets.only(right: 3),
      child: BaseClearButton(onPress: _clear),
    );
  }

  String _showText(List<BaseKeyValueModel> model) {
    String _show = "";
    model.asMap().keys.forEach((index) {
      if (model.length == 1 || index == model.length - 1) {
        _show += "[${model[index].key}]${model[index].value}";
      } else {
        _show += "[${model[index].key}]${model[index].value}/";
      }
    });
    return _show;
  }

  void _clear() {
    ///清除全部
    selectedList.clear();
    if (baseRequestFormProvider.dataSource.containsKey(model.fieldName)) {
      baseRequestFormProvider.dataSource[model.fieldName] = [];
    }
    setState(() {});
  }

  void _openFuzzySearchScreen() {
    BaseComponentUtils.buildDefaultBottomSheet(
      context,
      hit: "请选择",
      height: fuzzySearchScreenHeight,
      child: AdvancedFilterFuzzySearchScreen(
        hintText: model.note,
        inputApi: inputApi,
        isMultipleChoice: model.inputType == BaseAdvancedFilterType.InputSearchMultipleChoice,
        completeEvent: _completeEvent,
        selectList: selectedList,
        childOnlyKey: childOnlyKey,
        childOnlyValue: childOnlyValue,
        childSearchKey: childSearchKey,
        childWidget: childSearchItem,
        method: method,
        params: params,
        isPaging: isPaging,
        notNeedSearch: notNeedSearch,
      ),
    );
  }

  void _completeEvent(List<BaseKeyValueModel> item) {
    selectedList.clear();
    selectedList.addAll(item);
    baseRequestFormProvider.setDataSource(model, item.map((e) => e.toJson()).toList());
    setState(() {});
  }

  /// 获取inputSearchModel
  AdvancedFilterInputSearchModel getInputSearchModel() {
    AdvancedFilterInputSearchModel inputSearchModel;
    if (model.otherParam != null && model.otherParam.containsKey("inputSearchModel")) {
      if (model.otherParam['inputSearchModel'] is AdvancedFilterInputSearchModel) {
        inputSearchModel = model.otherParam['inputSearchModel'];
      }
    }
    return inputSearchModel == null ? null : inputSearchModel;
  }

  /// 获取childSearchItem
  Widget getChildSearchItem(Map<String, dynamic> item, bool isSelect) {
    if (getInputSearchModel().childSearchItem == null) return defaultChildSearchItem(item, isSelect);
    Widget searchItem = getInputSearchModel().childSearchItem(item, isSelect);
    return searchItem;
  }

  Widget defaultChildSearchItem(Map<String, dynamic> item, bool isSelect) {
    String childKey = BaseUtils.getKeyData(item, childOnlyKey);
    String childValue = BaseUtils.getKeyData(item, childOnlyValue);
    TextStyle valueStyle = TextStyle(fontSize: 15, color: Color(0xFF333333));
    TextStyle keyStyle = TextStyle(fontSize: 13, color: Color(0xFF868686));
    return Container(
      height: 80,
      padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      color: Colors.white,
      child: Column(
        children: [
          Expanded(
            child: Row(
              children: [
                Expanded(child: Row(children: [Text("[$childKey]", style: keyStyle), Text(childValue, style: valueStyle)])),
                Container(
                  width: 24,
                  height: 24,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(color: isSelect ? Color(0xFFFF004F) : Colors.white, shape: BoxShape.circle, border: Border.all(color: isSelect ? Color(0xFFFF004F) : Color(0xFFCCCCCC))),
                  child: Icon(BaseIconData.x3Checked, size: 16, color: isSelect ? Colors.white : Colors.transparent),
                ),
              ],
            ),
          ),
          BaseComponentUtils.buildHorizontalDivider(),
        ],
      ),
    );
  }
}
